let DateUtil = require("../../utils/dateUtil");
let playerScoreLoader = require("../entities/playerScore").loadFromDocument;
let playerScoreCreator = require("../entities/playerScore").create;

function GameRecord() {
    this.gameId = "";
    this.tableId = "";
    this.time = 0;
    this.playerScores = [];
}

GameRecord.prototype.toBSON = function() {
    let serializePlayerScores = [];
    for(let playerScore of this.playerScores) {
        serializePlayerScores.push(playerScore.toBSON());
    }
    return {
        gameId : this.gameId,
        tableId: this.tableId,
        time : this.time,
        playerScores : serializePlayerScores
    };
};

GameRecord.prototype.toJSON = function () {
    let  serializePlayerScores = [];
    for(let playerScore of this.playerScores) {
        serializePlayerScores.push(playerScore.toJSON());
    }
    return {
        gid : this.gameId,
        tid : this.tableId,
        time :Math.round(this.time / 1000),
        playerScores : serializePlayerScores
    };

};

module.exports.create = function(gameId, tableId, time, playerScores) {
    let gameRecord = new GameRecord();
    gameRecord.gameId = gameId;
    gameRecord.tableId = tableId;
    gameRecord.time = time;
    gameRecord.playerScores = [];

    for(let playerScore of playerScores) {
        gameRecord.playerScores.push(playerScoreCreator(playerScore.uid, playerScore.nickname, playerScore.score));
    }
    return gameRecord;
};

module.exports.loadFromDocument = function (document) {
    let gameRecord = new GameRecord();
    gameRecord.gameId = document["gameId"];
    gameRecord.tableId = document["tableId"];
    gameRecord.time = document["time"];
    gameRecord.playerScores = [];
    for(let playerScore of document.playerScores) {
        gameRecord.playerScores.push(playerScoreLoader(playerScore));
    }
    return gameRecord;
};
